import json
import requests
from datetime import datetime
import os
from tqdm import tqdm

def get_filename():
    return datetime.now().strftime("%Y-%m-%d-%H-%M-%S-%f")


if __name__=="__main__":
    try:
        page_size = int(input("请输入要爬取多少个视频："))
        #爬取视频的接口地址
        url = f"https://www.ku6.com/video/feed?pageNo=0&"\
              f"pageSize={page_size}&subjectId=76"
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36'
        }
        page_text = requests.get(url=url,headers=headers)
        #如果返回的是一个字符串，用text
        #把json字符串转成字典
        page_dic = json.loads(page_text.text)
        for item in page_dic["data"]:
            #获取到的视频地址
            video_url = item["playUrl"]
            #拿到视频地址之后，  将视频下载到本地
            #获取到视频的是二进制数据，用content
            video_data = requests.get(video_url,headers=headers)

            #获取到视频的大小，单位是b
            if "content-length" in video_data.headers:
                content_size = int(video_data.headers["content-length"])
            #获取到保存的视频名称
                video_name = get_filename()

            # with open(f"videos/{get_filename()}.mp4", "wb") as fp:
            #     fp.write(video_data.content)

            with open(f"videos/{get_filename()}.mp4",'wb') as fp,tqdm(  #设置爬取的进度
                desc = video_name,
                total = content_size
            ) as bar:
                    for chunk in video_data.iter_content(chunk_size=1024):
                        if chunk:
                            fp.write(chunk)
                            #加进度条
                            bar.update(len(chunk))

    except Exception as e:
        print(e)


